package com.example.binjiangapp.DAO.Dto;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.binjiangapp.common.AjaxResult;
import com.example.binjiangapp.common.utils.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private ObjectMapper objectMapper;


    /**
     * 此方法会在进入controller之前执行，返回Boolean值决定是否执行后续操作。
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");

        if (request.getRequestURI().contains("login")) {
            return true;
        }

        if (StrUtil.isBlank(token)) {

            response.setContentType("application/json;charset=utf-8");
            String result = objectMapper.writeValueAsString(AjaxResult.error( "token不能为空", null));
            response.getWriter().write(result);
            return false;
        }

        DecodedJWT decodedJWT = JwtUtils.parseToken(token);
        if (decodedJWT == null) {
            response.setContentType("application/json;charset=utf-8");
            String result = objectMapper.writeValueAsString(AjaxResult.error( "登录超时", null));
            response.getWriter().write(result);
            return false;
        }

        String username = decodedJWT.getClaim("username").asString();

        request.setAttribute("username", username);

        return true;
    }

    /**
     * 此方法将在controller执行之后执行，但是视图还没有解析，可向ModelAndView中添加数据(前后端不分离的)。
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("controller 执行完了");
    }

    /**
     *  该方法会在整个请求结束（请求结束，但是并未返回结果给客户端）之后执行， 可获取响应数据及异常信息。
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("我获取到了一个返回的结果："+response);
        System.out.println("请求结束了");
    }
}
